
import { AudioManager } from "../../frame/component/audio-manager";
import NativeClient from "../../frame/native/NativeClient";
import { NCAPIURI, NCBody, NCPoint, NCPointData, NCResponse, NCResult } from "./api.config.client";

type URIRequest = {[uri in NCAPIURI]: {} extends NCResult<uri> ? never : uri}[NCAPIURI];
type URISend = {[uri in NCAPIURI]: {} extends NCResult<uri> ? uri : never}[NCAPIURI];

export class ClientAPI {
	private static async request<uri extends URIRequest>(api: uri, data?: NCBody<uri>, ccdata?: any){
		let struct = NativeClient.sendMessage(api, data, true, ccdata);
		return struct.response as NCResponse<uri>;
	}

	private static send<uri extends URISend>(api: uri, data?: NCBody<uri>){
		NativeClient.sendMessage(api, data, false);
	}

	/** 获取设备ID */
	public static async DeviceID(){
		let response = await ClientAPI.request(NCAPIURI.DeviceID);
		return response.data.device_id;
	}

	/** 本地化接口 */
	public static async Local(){
		let response = await ClientAPI.request(NCAPIURI.LOCAL);
		return response.data;
	}

	/** 广告请求 */
	public static async AD(type: NCBody<NCAPIURI.AD>['type']){
		ClientAPI.Float();
		AudioManager.pauseBgm();
		let response = await ClientAPI.request(NCAPIURI.AD, {type}, mtec.string.random(5, 36));
		AudioManager.playBGM();
		return response.data.status == 'ad-over';
	}

	/** 获取游戏类型 */
	public static async GameType(){
		let response = await ClientAPI.request(NCAPIURI.GameType);
		return response.data;
	}

	/** 设置剪贴板 */
	public static SetClipboard(text: NCBody<NCAPIURI.SetClipboard>['text']){
		ClientAPI.send(NCAPIURI.SetClipboard, {text});
	}

	public static Float(){
		ClientAPI.send(NCAPIURI.Float);
	}

	/** 评分弹窗 */
	public static ScorePop(){
		ClientAPI.send(NCAPIURI.ScorePop);
	}

	public static CloseLoading(){
		ClientAPI.send(NCAPIURI.CloseLoading);
	}

	public static Point<P extends NCPoint>(point: P, data: Partial<NCPointData<P>>){
		let list: string[] = [];

		Reflect.ownKeys(data).forEach(key=>{
			let v = Reflect.get(data, key);
			let t = typeof v;
			if(!['number', 'string', 'boolean', 'bigint'].includes(t)){
				return void 0;
			}

			if(t=='bigint'){
				t = 'number';
			}

			list.push(String(key) + '@' + ({number: 'N', string: 'S', boolean: 'B'})[t] + ':' + String(v));
		});

		if(list.length>0){
			ClientAPI.send(NCAPIURI.Point, {point, value: list.join(';')});
		}
	}
}
